﻿using BaiTu.Framework.MVCFramework.Descriptors;
using BaiTu.Framework.MVCFramework.Parsers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Script.Serialization;

namespace BaiTu.Framework.MVCFramework.HttpHandlers
{
    public class JsonHttpHandler : IHttpHandler
    {
        private ControllerDescriptor controllerDescriptor;
        private MethodDescriptor methodDescriptor;
        private JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();

        public JsonHttpHandler(ControllerDescriptor controllerDescriptor, MethodDescriptor methodDescriptor)
        {
            this.controllerDescriptor = controllerDescriptor;
            this.methodDescriptor = methodDescriptor;
        }

        public bool IsReusable
        {
            get { throw new NotImplementedException(); }
        }


        public void ProcessRequest(HttpContext context)
        {
            MethodInfo mi = this.controllerDescriptor.ControllerType.GetMethod(this.methodDescriptor.MethodName);

            List<object> parameters = new List<object>();

            foreach (var pd in this.methodDescriptor.ParameterDescriptors)
            {
                object value = ParameterParser.GetValue(context, pd);
                parameters.Add(value);
            }


            object result = mi.Invoke(null, parameters.ToArray());
            string json = jsonSerializer.Serialize(result);
            context.Response.Write(json);
        }
    }
}
